package com.atguigu.acl.controller;


import cn.hutool.core.collection.CollUtil;
import com.atguigu.acl.bo.AdminUserDetails;
import com.atguigu.acl.dto.AdminLoginParam;
import com.atguigu.acl.entity.Admin;
import com.atguigu.acl.entity.Permission;
import com.atguigu.acl.entity.Role;
import com.atguigu.acl.service.AdminService;
import com.atguigu.acl.service.MenuService;
import com.atguigu.common.Result;
import com.atguigu.serviceBase.exception.GuliException;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.map.HashedMap;
import org.springframework.boot.autoconfigure.kafka.KafkaProperties;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 管理员表 前端控制器
 * </p>
 *
 * @author smday
 * @since 2020-08-10
 */
@RestController
@RequestMapping("/admin")
public class AdminController {

    private static final String tokenHead = "Bearer ";
    private static final String tokenHeader = "Authorization";
    @Resource
    private AdminService adminService;
    @Resource
    private MenuService menuService;

    @ApiOperation(value = "登录以后返回token")
    @PostMapping("/login")
    public Result login(@RequestBody AdminLoginParam adminLoginParam) {
        //返回token
        String token = adminService.login(adminLoginParam.getUsername(), adminLoginParam.getPassword());

        if (token == null) {
            throw new GuliException("用户名或密码错误");
        }

        return Result.ok().data("token", token).data("tokenHead", tokenHead);

    }

    @ApiOperation(value = "刷新token")
    @GetMapping("/refreshToken")
    public Result refreshToken(HttpServletRequest request) {
        String token = request.getHeader(tokenHeader);
        String refreshToken = adminService.refreshToken(token);
        if (refreshToken == null) {
            throw new GuliException("token已经过期！");
        }
        Map<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("token", refreshToken);
        tokenMap.put("tokenHead", tokenHead);
        return Result.ok().data(tokenMap);
    }

    @ApiOperation(value = "获取登录账号的信息")
    @GetMapping("/info")
    public Result getAdminInfo() {

        AdminUserDetails userDetails = (AdminUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        if (userDetails == null) {
            return Result.unauthorized();
        }
        String username = userDetails.getUsername();
        Admin admin = adminService.getAdminByUsername(username);
        Map<String, Object> map = new HashedMap<>();
        //将用户信息 :基本信息+角色信息
        List<Role> roleList = adminService.getRoleList(admin.getId());
        if (CollUtil.isNotEmpty(roleList)) {
            List<String> roles = roleList.stream().map(Role::getName).collect(Collectors.toList());
            map.put("roles", roles);
        }
        map.put("username", admin.getUsername());
        map.put("menus", menuService.getMenuList(admin.getId()));
        map.put("icon", admin.getIcon());

        return Result.ok().data(map);
    }

    @ApiOperation("修改指定用户信息")
    @PostMapping("/update/{id}")
    public Result update(@PathVariable Long id, @RequestBody Admin admin) {
        int count = adminService.update(id, admin);
        if (count > 0) {
            return Result.ok().data("count",count);
        }
        return Result.error();
    }


    @ApiOperation("新增用户")
    @PostMapping("/insert")
    public Result insert(@RequestBody Admin admin){
        int count = adminService.insert(admin);
        if (count > 0) {
            return Result.ok().data("count",count);
        }
        return Result.error();
    }


    @ApiOperation(value = "登出功能")
    @PostMapping("/logout")
    public Result logout() {
        return Result.ok();
    }

    @ApiOperation("给用户分配角色")
    @PostMapping("/role/update")
    public Result updateRole(@RequestParam("adminId") Long adminId,
                             @RequestParam("roleIds") List<Long> roleIds){
        int count = adminService.updateRole(adminId, roleIds);
        if(count>=0){
            return Result.ok().data("count",count);
        }
        return Result.error();
    }

    @ApiOperation("根据用户名或姓名分页获取用户列表")
    @GetMapping("/list")
    public Result list(@RequestParam(value = "keyword", required = false) String keyword,
                                                   @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                                                   @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        Map<String, Object> map = adminService.list(keyword, pageSize, pageNum);
        return Result.ok().data(map);
    }

    @ApiOperation("获取指定用户信息")
    @GetMapping("/{id}")
    public Result getItem(@PathVariable Long id) {
        Admin admin = adminService.getItem(id);
        return Result.ok().data("admin",admin);
    }

    @ApiOperation("获取指定用户角色")
    @GetMapping("/role/{adminId}")
    public Result getRoleList(@PathVariable Long adminId){
        List<Role> roleList = adminService.getRoleList(adminId);
        return Result.ok().data("roleList",roleList);
    }


    @ApiOperation("删除指定用户信息")
    @PostMapping("/delete/{id}")
    public Result delete(@PathVariable Long id) {
        int count = adminService.delete(id);
        if (count > 0) {
            return Result.ok().data("count",count);
        }
        return Result.error();
    }

    @ApiOperation("修改帐号状态")
    @PostMapping("/updateStatus/{id}")
    public Result updateStatus(@PathVariable Long id,@RequestParam(value = "status") Integer status) {
        Admin admin = new Admin();
        admin.setStatus(status);
        int count = adminService.update(id,admin);
        if (count > 0) {
            return Result.ok().data("count",count);
        }
        return Result.error();
    }


    @ApiOperation("给用户分配+-权限")
    @PostMapping("/permission/update")
    public Result updatePermission(@RequestParam Long adminId,
                                         @RequestParam("permissionIds") List<Long> permissionIds) {
        int count = adminService.updatePermission(adminId, permissionIds);
        if (count > 0) {
            return Result.ok().data("count",count);
        }
        return Result.error();
    }

    @ApiOperation("获取用户所有权限（包括+-权限）")
    @GetMapping(value = "/permission/{adminId}")
    public Result getPermissionList(@PathVariable Long adminId) {
        List<Permission> permissionList = adminService.getPermissionList(adminId);
        return Result.ok().data("permissionList",permissionList);
    }

}

